//
//  BonusNode.m
//  iFly
//
//  Created by User-10 on 12/7/14.
//  Copyright (c) 2014 TeamDifferent. All rights reserved.
//

#import "BonusNode.h"
#import "CharacterNode.h"

@implementation BonusNode

+(instancetype)bonusWithImageNamed:(NSString*)image andPosition:(CGPoint)position {
    
    BonusNode* bonus = [self spriteNodeWithImageNamed:image];
    
    //adding physics body for collision detection for bonuses
    bonus.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:bonus.size];
    bonus.physicsBody.categoryBitMask = bonusCategory;
    bonus.physicsBody.affectedByGravity = NO;
    bonus.physicsBody.dynamic = YES;
    bonus.physicsBody.contactTestBitMask = characterCategory|shieldCategory;
    bonus.physicsBody.collisionBitMask = 0;
    bonus.physicsBody.usesPreciseCollisionDetection = YES;
    bonus.name = @"bonus";
    
    bonus.position = position;
    
    return bonus;
}

-(void) move {
    CGPoint target = CGPointMake(0, self.position.y);
    
    int duration = 5.0;
    
    SKAction* move = [SKAction moveTo:target duration:duration];
    SKAction* moveDone = [SKAction removeFromParent];
    [self runAction:[SKAction sequence:@[move, moveDone]]];
}

-(void) wasTaken {
    //play coin sound
    [[SoundHandler sharedSoundPlayer] playSoundWithName:@"coinSound" andType:@"wav"];
    
    SKEmitterNode *emitter =  [NSKeyedUnarchiver unarchiveObjectWithFile:[[NSBundle mainBundle] pathForResource:@"Spark" ofType:@"sks"]];
    emitter.position = self.position;
    emitter.name = @"Spark";
    [self.parent addChild:emitter];
    
    SKAction* fadeEmitter = [SKAction fadeAlphaTo:0.0 duration:2];
    SKAction* remove = [SKAction removeFromParent];
    SKAction* sequence = [SKAction sequence:@[fadeEmitter, remove]];
    [emitter runAction:sequence];

    CharacterNode* character= (CharacterNode*)[self.parent childNodeWithName:@"character"];
    [character addScore:self.points];

    [self removeFromParent];
}

@end
